/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.Reward;
import cn.hpclub.server.model.SalePromotion;
import cn.hpclub.server.util.HttpUtil;

/**
 * Class description goes here
 *
 * @author
 */
public class ApiService{

    private static final Logger logger     = LoggerFactory.getLogger(ApiService.class);
    public static ApiService    service    = new ApiService();
    private String              URL_DECODE = "http://120.25.225.52:7080/dpr/service/decFxStr.json";

    public void rechargeCallback(HttpServletRequest request) throws Exception{
        logger.debug("rechargeCallback start");
        File configFile = null;
        Document document = null;
        String DATA = "/root/data/";
        String fx = null;
        ServletInputStream is = request.getInputStream();
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while((ch = is.read()) != -1){
            bytestream.write(ch);
        }
        is.close();
        byte[] result = bytestream.toByteArray();
        logger.debug("rechargeCallback =" + new String(result));
        updateRecord(new String(result), request.getRemoteAddr());
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(new ByteArrayInputStream(result));

        SalePromotion sale = new SalePromotion();
        sale.set(SalePromotion.ID, 0);
        sale.set(SalePromotion.APPID, Constant.APPID);
        sale.set(SalePromotion.ORDER_ID, document.selectSingleNode(DATA + SalePromotion.ORDER_ID).getText().trim());
        sale.set(SalePromotion.AMOUNT,
                 Integer.parseInt(document.selectSingleNode(DATA + SalePromotion.AMOUNT).getText().trim()));
        sale.set(SalePromotion.PHONE_NO, document.selectSingleNode(DATA + SalePromotion.PHONE_NO).getText().trim());
        sale.set(SalePromotion.TIME, document.selectSingleNode(DATA + SalePromotion.TIME).getText().trim());
        sale.set(SalePromotion.IS_USED, 0);
        sale.set(SalePromotion.USED_TIME, null);
        sale.set(SalePromotion.WIN_TYPE, null);
        sale.set(SalePromotion.WIN_NAME, null);
        // sale.set(SalePromotion.STOREID,
        // Integer.parseInt(document.selectSingleNode(DATA +
        // SalePromotion.STOREID).getText().trim()));
        sale.set(SalePromotion.RETURN_CODE,
                 document.selectSingleNode(DATA + SalePromotion.RETURN_CODE).getText().trim());
        sale.set(SalePromotion.RETURN_MSG, document.selectSingleNode(DATA + SalePromotion.RETURN_MSG).getText().trim());

        sale.set(SalePromotion.INTE_RES_CODE, null);
        sale.set(SalePromotion.INTE_RES_MSG, null);
        sale.set(SalePromotion.ISDELETE, 0);
        sale.set(SalePromotion.ISFIXDATA, 0);
        sale.set(SalePromotion.XMLDATA, document.asXML());

        if(document.selectSingleNode(DATA + SalePromotion.THIRDPART_ID) != null){// 充值缴费回调
            // Record r = Db.findFirst("select " + MemberOrg.ID + "," +
            // MemberOrg.ORG_ID + " from "
            // + Constant.Table.MEMBER_ORG + " where " + MemberOrg.USER_NAME +
            // "="
            // + document.selectSingleNode(DATA + "username").getText().trim());
            // sale.set(SalePromotion.ORG_ID, r.getInt(MemberOrg.ORG_ID));
            // sale.set(SalePromotion.USERID, r.getInt(MemberOrg.ID));
            // sale.set(SalePromotion.BUSINESS_CODE, "4001");
            sale.set(SalePromotion.SYSTEMID, 0);
            sale.set(SalePromotion.SOURCE, 0);
            sale.set(SalePromotion.METHOD, null);
            String[] foreign_content = document.selectSingleNode(DATA + "foreign_content").getText().trim().split("_");
            for(int i = 0; i < foreign_content.length; i++){
                if(foreign_content[i].contains("saleType")){
                    sale.set(SalePromotion.SALETYPE,
                             foreign_content[i].substring(foreign_content[i].lastIndexOf('=') + 1));
                }
                if(foreign_content[i].contains(SalePromotion.FXSTR)){
                    sale.set(SalePromotion.FXSTR,
                             foreign_content[i].substring(foreign_content[i].lastIndexOf('=') + 1));

                }
                if(foreign_content[i].contains(SalePromotion.MODULEID)){
                    sale.set(SalePromotion.MODULEID,
                             Integer.parseInt(foreign_content[i].substring(foreign_content[i].lastIndexOf('=') + 1)));

                }
            }

            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put(SalePromotion.FXSTR, sale.getStr(SalePromotion.FXSTR));
            fx = HttpUtil.getHttpByGet(URL_DECODE, hm);
            // fx =
            // "{\"params\":\"11#10407088#5291680#20160217002809#1095602#4001#Q1o=\"}";
            logger.debug("rechargeCallback fx=" + fx);
            foreign_content = new JSONObject(fx).getString("params").split("#");
            sale.set(SalePromotion.BUSINESS_CODE, foreign_content[5]);
            sale.set(SalePromotion.USERID, Integer.parseInt(foreign_content[2]));
            Record r = Db.findFirst("select " + MemberOrg.ORG_ID + " from " + Constant.Table.MEMBER_ORG + " where "
                    + MemberOrg.ID + "=" + foreign_content[2].trim());
            sale.set(SalePromotion.ORG_ID, r.getInt(MemberOrg.ORG_ID));
            sale.set(SalePromotion.MODULECODE, 8000);
        } else{
            Record r = Db.findFirst("select " + MemberOrg.ORG_ID + " from " + Constant.Table.MEMBER_ORG + " where "
                    + MemberOrg.ID + "=" + document.selectSingleNode(DATA + SalePromotion.USERID).getText().trim());
            sale.set(SalePromotion.ORG_ID, r.getInt(MemberOrg.ORG_ID));
            // sale.set(SalePromotion.ORG_ID,
            // Integer.parseInt(document.selectSingleNode(DATA +
            // SalePromotion.STOREID).getText().trim()));
            sale.set(SalePromotion.USERID,
                     Integer.parseInt(document.selectSingleNode(DATA + SalePromotion.USERID).getText().trim()));
            sale.set(SalePromotion.BUSINESS_CODE,
                     document.selectSingleNode(DATA + SalePromotion.BUSINESS_CODE).getText().trim());
            sale.set(SalePromotion.SYSTEMID,
                     Integer.parseInt(document.selectSingleNode(DATA + SalePromotion.SYSTEMID).getText().trim()));
            sale.set(SalePromotion.SOURCE,
                     Integer.parseInt(document.selectSingleNode(DATA + SalePromotion.SOURCE).getText().trim()));
            sale.set(SalePromotion.METHOD, document.selectSingleNode(DATA + "methodName").getText().trim());
            sale.set(SalePromotion.SALETYPE,
                     Integer.parseInt(document.selectSingleNode(DATA + SalePromotion.SALETYPE).getText().trim()));
            sale.set(SalePromotion.FXSTR, null);
            String[] foreign_content = document.selectSingleNode(DATA + "foreign_content").getText().trim().split("_");
            int moduleId = 0;
            String moduleCode = "";
            for(int i = 0; i < foreign_content.length; i++){
                if(foreign_content[i].contains(SalePromotion.MODULEID)){
                    moduleId = Integer.parseInt(foreign_content[i].substring(foreign_content[i].lastIndexOf('=') + 1));

                }

                if(foreign_content[i].contains(SalePromotion.MODULECODE)){
                    moduleCode = foreign_content[i].substring(foreign_content[i].lastIndexOf('=') + 1);

                }
            }
            sale.set(SalePromotion.MODULECODE, moduleCode);
            sale.set(SalePromotion.MODULEID, moduleId);

        }

        List<Record> listReward = SalePromotion.dao
                .findReward(sale.getInt(SalePromotion.USERID), sale.getStr(SalePromotion.BUSINESS_CODE),
                            sale.getInt(SalePromotion.ORG_ID), sale.getInt(SalePromotion.MODULEID));

        if(listReward == null || listReward.size() <= 0
                || Integer.parseInt(sale.getStr(SalePromotion.RETURN_CODE)) != 0){
            sale.set(SalePromotion.REWARD, 0.00);
        } else{
            Record reward = listReward.get(0);
            Double temp = 0.00;
            Double sum = reward.getBigDecimal("sum").doubleValue();
            Double sumModule = reward.getBigDecimal("sumModule").doubleValue();
            Double clerk = 0.00;
            boolean tag_module = false;
            boolean tag_sum = false;
            if(reward.getLong("count") <= 0){
                temp = reward.getBigDecimal(Reward.FIRST_REWARD).doubleValue();
            } else{
                temp = reward.getBigDecimal(Reward.NORMAL_REWARD).doubleValue();
            }

            List<Record> listClerk = SalePromotion.dao.findClerkReward(sale.getInt(SalePromotion.MODULEID),
                                                                       sale.getInt(SalePromotion.ORG_ID));
            if(listClerk != null && listClerk.size() >= 1){
                for(Record r : listClerk){
                    if(r.getInt("moduleid") == sale.getInt(SalePromotion.MODULEID)){
                        clerk = r.getBigDecimal("single_cap").doubleValue() <= 0 ? Double.MAX_VALUE
                                : r.getBigDecimal("single_cap").doubleValue();

                        sumModule = sumModule >= clerk ? 0.00 : clerk - sumModule;
                        tag_module = true;
                        // sumModule = sumModule >=
                        // r.getBigDecimal("single_cap").doubleValue() ? 0.00
                        // : r.getBigDecimal("single_cap").doubleValue() -
                        // sumModule;
                    } else{
                        clerk = r.getBigDecimal("single_cap").doubleValue() <= 0 ? Double.MAX_VALUE
                                : r.getBigDecimal("single_cap").doubleValue();

                        sum = sum >= clerk ? 0.00 : clerk - sum;
                        tag_sum = true;
                        // sum = sum >=
                        // r.getBigDecimal("single_cap").doubleValue() ? 0.00
                        // : r.getBigDecimal("single_cap").doubleValue() - sum;
                    }
                }
            }

            if(!tag_module){
                sumModule = Double.MAX_VALUE;
            }
            if(!tag_sum){
                sum = Double.MAX_VALUE;
            }
            temp = min(temp, sum, sumModule);

            sale.set(SalePromotion.REWARD, temp);

        }

        sale.save();

    }

    private double min(double reward, double sum, double sumModule){
        double min = reward;
        if(sum < min){
            min = sum;
        }
        if(sumModule < min){
            min = sumModule;
        }
        return Double.parseDouble(new DecimalFormat("######0.00").format(min));
    }

    private void updateRecord(String xml, String host){
        try{
            Db.update("insert into sales_promotion_record value(0,?,date_format(now(),'%Y-%m-%d  %H:%i:%s'),?)",
                      new Object[] { xml, host });
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

}
